<?php

namespace app\mpbase\library;
use app\mpbase\service\Config as ConfigService;
use think\Request;
use app\admin\model\HkStore;

class QrCode {

	public $appid;
	public $secret;
	public $access_token;
	public $app = null;
	public $miniProgram = null;
	public $appletId = null;
	public $options = [];
	public function __construct(){
		//应用初始化
		$appletId = Request::instance()->header('appletId');
		$appletId = input('appletId', $appletId);
		//如果不存在 到Session 中取appletid (后台Session)
		$appletId == null && $appletId = session('applet_info.appletid');
		$this->appletId = $appletId ;

		//获取应用配置信息
		$this->options = ConfigService::load($appletId);
		$this->appid = $this->options['mini_program']['app_id'];
		$this->secret = $this->options['mini_program']['secret'];
	}


	//用小程序的appid appsecret获取token
	public function get_access_token()
	{
		$appid = $this->appid;
		$secret = $this->secret;
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
		return $data = $this->curl_get($url);
	}

	//发送curl请求
	public function curl_get($url)
	{
		$curl = curl_init();
		curl_setopt($curl,CURLOPT_URL,$url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$data = curl_exec($curl);
		$err = curl_error($curl);
		curl_close($curl);
		return $data;
	}

	//获得二维码
	public function get_qrcode($name,$sceneId,$page)
	{
			header('content_type:image/jpeg');
			$data          = array();
			$data['scene'] = "scene=" . $sceneId;
			$data['page']  = $page;
			$data          = json_encode($data);
			$access        = json_decode($this->get_access_token(), true);
			$access_token  = $access['access_token'];
			$url           = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
			$file_name            = $this->get_http_array($name,$url, $data);
			return $file_name;

	}

	public function get_http_array($name,$url,$post_data) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   //没有这个会自动输出，不用print_r();也会在后面多个1
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		ob_start();//开启
		$output = curl_exec($ch);
		$content = ob_get_contents();
		file_put_contents($name,$content);
		ob_end_clean();
		curl_close($ch);
		$out = json_decode($output);
		return $name;
	}
}